package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.one.group.service.ChatHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(String type, String chatId) {
        String key = buildKey(type);
        // 使用 Set 避免重复添加
        redisTemplate.opsForSet().add(key, chatId);
    }

    @Override
    public List<String> getChatIds(String type) {
        String key = buildKey(type);
        Set<String> chatIds = redisTemplate.opsForSet().members(key);
        return chatIds != null ? new ArrayList<>(chatIds) : Collections.emptyList();
    }
    // 构建 Redis Key，例如：chat:history:{userId}:{type}
    private String buildKey(String type) {
        Long userId = Convert.toLong(StpUtil.getLoginId());
        if (userId == null ) {
            throw new RuntimeException("当前线程未设置用户ID");
        }
        return "chat:history:" + userId + ":" + type;
    }
}
